#pragma once
#include <iostream>
#include <string.h>

#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "log.hpp"

Log lg;

class Task
{
public:
    Task(int sockfd, std::string clientip, uint16_t clientport)
        : _sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {}

    void run()
    {
        char buffer[1024];
        while (true)
        {
            memset(buffer, 0, sizeof(buffer));
            // 首先从sockfd中读数据
            int n = read(_sockfd, buffer, sizeof(buffer));
            // 如果读到了数据就直接进行处理
            if (n > 0)
            {
                // 进行处理数据
                std::cout << "client say#" << buffer << std::endl;
                std::string echostr = "server#";
                echostr += buffer;

                // 再将处理后的数据写入sockfd中让客户端读取
                int m = write(_sockfd, echostr.c_str(), echostr.size());
                if (m < 0)
                {
                    lg(WARNING, "write error,errno:%d,errnostring:%s", errno, strerror(errno));
                }
            }
            else if (n == 0)
            {
                lg(INFO, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
                break;
            }
            else
            {
                lg(WARNING, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _clientip.c_str(), _clientport);
                break;
            }
        }
    }

    void operator()()
    {
        run();
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};